package com.leyou.upload.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.upload.config.OSSProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Service
public class UploadService {

    //图片上传路径
    private final static String IMAGE_FILE_PATH = "C:\\Users\\Yzhaot\\Desktop\\leyou\\software\\nginx-1.16.0\\html\\brand-img";
    //图片服务器名称
    private final static String IMAGE_URL = "http://image.leyou.com/brand-img/";
    //允许上传图片的格式
    private final static List<String> ALLOW_UPLOAD_IMAGE = Arrays.asList("image/png","image/jpeg");

    //oss客户端
    @Autowired
    private OSS ossClient;
    //oss配置类
    @Autowired
    private OSSProperties prop;


    public String upload(MultipartFile file) {
        //判断图片上传的文件类型
        if (!ALLOW_UPLOAD_IMAGE.contains(file.getContentType())){
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        //判断用户上传的图片是否是真实的图片信息
        try{
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null){
                throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
            }
        }catch (IOException e){
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }

        File imagePathFile = new File(IMAGE_FILE_PATH);
        String imageName = UUID.randomUUID() + file.getOriginalFilename();
        try {
            /**
             *  参数一: 上传到哪个目录
             *  参数二: 图片名称
             */
            file.transferTo(new File(imagePathFile, imageName));
        } catch (IOException e){
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        }
        //图片访问路径
        return IMAGE_URL + imageName;
    }

    public void deleteImage(String url) {
        String imageName = url.substring(url.lastIndexOf("/") + 1);
        String imageFilePath = IMAGE_FILE_PATH + "\\" + imageName;
        System.out.println("imageFilePath = " + imageFilePath);
        File file = new File(imageFilePath);
        file.delete();
    }

    public Map<String, Object> signature() {
        try {
            long expireTime = prop.getExpireTime();
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, prop.getMaxFileSize());
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, prop.getDir());

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            Map<String, Object> respMap = new LinkedHashMap<>();
            respMap.put("accessId", prop.getAccessKeyId());
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", prop.getDir());
            respMap.put("host", prop.getHost());
            respMap.put("expire", expireEndTime);

            return respMap;
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
    }
}
